package com.example.demo.Util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;

public class HBaseUtils {
    /**
     * @param  "indata-10-111-24-197.indata.com,indata-10-111-24-198.indata.com,indata-10-111-24-199.indata.com"
     * @return Configuration
     */
    public static Configuration initConfiguration() throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum",
                "indata-10-10-2-11.indata.com,indata-10-10-2-12.indata.com,indata-10-10-2-13.indata.com");
        conf.set("zookeeper.znode.parent", "/hbase-secure");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conf.set("hadoop.security.authentication", "kerberos");
        conf.set("hadoop.security.authorization", "true");
        conf.set("hbase.security.authentication", "kerberos");
        conf.set("hbase.security.authorization", "true");
        // HMaster地址
        conf.set("hbase.master.kerberos.principal", "hbase/_HOST@INDATA.COM");
        conf.set("hbase.regionserver.kerberos.principal", "hbase/_HOST@INDATA.COM");
        return conf;
    }

    public static void authenticate(Configuration conf) throws IOException {
        if ("kerberos".equalsIgnoreCase(conf.get("hbase.security.authentication"))) {
            String krbStr = "F:\\krb5.conf";
            System.setProperty("java.security.krb5.conf", krbStr);
            System.setProperty("java.security.krb5.realm", "INDATA.COM");
            System.setProperty("java.security.krb5.kdc", "indata-10-111-24-197.indata.com");
            String principal = "hbase-cluster1@INDATA.COM";
            String keytabFilePath = "F:\\yzhshow-realm.keytab";
            UserGroupInformation.setConfiguration(conf);
            UserGroupInformation.loginUserFromKeytab(principal, keytabFilePath);
            System.out.println("登陆成功！");
        }
    }
    public static Connection getConnection(Configuration conf) throws IOException {
        return ConnectionFactory.createConnection(conf);
    }
    public static Connection returnConnection() throws IOException {
        Configuration conf = initConfiguration();
        Connection connection = null;
        try {
            authenticate(conf);
            connection = getConnection(conf);
        } catch (Throwable e) {
            System.out.println(e.getMessage());
            String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
            System.out.println("打印异常2:" + fullStackTrace);
        }
        return connection;
    }
}
